import config from '../config.js'
import md5 from './md5.js'

const baseOpt = {
	domain: config.domain,
	data: {},
	header: {},
	method: 'post',
	timeout: 40000,
	dataType: 'json',
	loading: true,
	loadText: '加载中',
	showError: true,
	storageUpdate: false,
	storageExpire: 0,
	isCustomResult: false,
	studyEnd: true
}

let http = (url, opts) => {
	opts = {
		...baseOpt,
		...opts
	}
	return new Promise((resolve, reject) => {
		// if (opts.loading) {
		// 	uni.showLoading({
		// 		title: opts.loadText,
		// 		mask: true
		// 	})
		// }
		let data = {
			url: opts.domain + url,
			data: {
				...opts.data,
			},
			header: {
				'content-type': 'application/json;charset=UTF-8',
				// 'x-auth-token': uni.$utils.getToken() || '',
				...opts.header
			},
		}
		// console.log('request', data, md5.md5(JSON.stringify(data)))
		if (!opts.storageUpdate && opts.storageExpire) {
			let res = uni.$utils.getStorageSyncTime(md5.md5(JSON.stringify(data)))
			if (res) {
				uni.hideLoading()
				resolve(res)
				// console.log('response缓存', res)
				return
			}
		}
		uni.request({
			...data,
			method: opts.method,
			timeout: opts.timeout,
			dataType: opts.dataType,
			success: (res) => {
				uni.hideLoading()
				if (res.data.code === 0 || res.data.status === 0 || res.data.statuscode === 1 || res.data.statuscode === 0) {
					resolve(res)
				} else {
					if (opts.showError) {
						uni.showToast({
							title: res.data.msg || '系统错误',
							icon: 'none',
							// mask: true,
							duration: 1500
						})
					}
					reject(res)
				}
			},
			fail: (err) => {
				if (opts.loading) {
					uni.hideLoading()
				}
				reject(err)
			},
			complete: () => {}
		})
	})
}

export default http
